package cn.yikaojiuguo.student.ui.global;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.view.View;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.yikaojiuguo.student.R;
import cn.yikaojiuguo.student.adapter.AblumImageAdapter;
import cn.yikaojiuguo.student.app.YiKaoApplication;
import cn.yikaojiuguo.student.bean.FolderBean;
import cn.yikaojiuguo.student.support.simple.ArgsConstants;
import cn.yikaojiuguo.student.support.utils.LogUtil;
import cn.yikaojiuguo.student.support.utils.Util;

public class AblumActivity extends Activity {

    @Bind(R.id.iv_back)
    ImageView mIv_back;
    @Bind(R.id.tv_operation)
    TextView mTv_operation;
    @Bind(R.id.gv)
    GridView mGv;
    @Bind(R.id.rl_bottom)
    RelativeLayout mRl_bottom;
    @Bind(R.id.tv_dir_name)
    TextView mTv_dir_name;
    @Bind(R.id.tv_dir_count)
    TextView mTv_dir_count;
    private ProgressDialog mProgressDialog;
    private List<FolderBean> mFolderBeans = new ArrayList<FolderBean>();
    private int mMaxCount;
    private File mCurrentDir;
    private static final int FINISH_LOAD = 1;
    // 存放要显示的图片的路径
    private List<String> mList;
    private AblumImageAdapter adapter;
    private ListImgDirPopupWindow popupWindow;
    private int mMax = 3;
    private ArrayList<String> mPicsPath;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == FINISH_LOAD) {
                mProgressDialog.dismiss();
                data2View();
                initPopupWindow();
            }
        }
    };

    public static Intent newIntent(int max,ArrayList<String> picsPath) {
        Intent intent = new Intent(YiKaoApplication.getInstance(),AblumActivity.class);
        intent.putExtra(ArgsConstants.MAX,max);
        intent.putStringArrayListExtra(ArgsConstants.PICS,picsPath);
        return intent;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ablum);
        ButterKnife.bind(this);
        initDatas();//遍历文件
        initEvents();//处理点击事件
    }

    private void initPopupWindow() {
        popupWindow = new ListImgDirPopupWindow(this,mFolderBeans);
        popupWindow.setAnimationStyle(R.style.anim_popup_from_bottom);
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                Util.lightOn(AblumActivity.this);
            }
        });
        popupWindow.setOnDirSelectedListener(new ListImgDirPopupWindow.OnDirSelectedListener() {
            @Override
            public void onSelected(FolderBean folderBean) {
                mCurrentDir = new File(folderBean.getDir());
                mList = Arrays.asList(mCurrentDir.list(new FilenameFilter() {
                    @Override
                    public boolean accept(File dir, String filename) {
                        if (filename.endsWith(".jpg") || filename.endsWith("jpeg") || filename
                                .endsWith(".png"))
                            return true;
                        return false;
                    }
                }));
                Collections.reverse(mList);
                adapter = new AblumImageAdapter(AblumActivity.this, mList, mCurrentDir.getAbsolutePath(),mMax,mPicsPath);
                mGv.setAdapter(adapter);
                mTv_dir_count.setText(mList.size() + "");
                mTv_dir_name.setText(folderBean.getName());
                popupWindow.dismiss();
            }
        });
    }

    /**
     * 绑定数据到View
     */
    private void data2View() {
        if (mCurrentDir == null) {
            Toast.makeText(this, "未扫描到任何图片", Toast.LENGTH_SHORT);
            return;
        }
        mList = Arrays.asList(mCurrentDir.list());
        Collections.reverse(mList);
        adapter = new AblumImageAdapter(this,mList,mCurrentDir.getAbsolutePath(),mMax,mPicsPath);
        mGv.setAdapter(adapter);
        mTv_dir_count.setText(mMaxCount + "");
        mTv_dir_name.setText(mCurrentDir.getName());

    }

    /**
     * 利用ContentProvider扫描手机中所有的图片
     */
    private void initDatas() {

        mMax = getIntent().getIntExtra(ArgsConstants.MAX,3);
        mPicsPath = getIntent().getStringArrayListExtra(ArgsConstants.PICS);
        if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            Toast.makeText(this, "SD卡不可用", Toast.LENGTH_SHORT);
            return;
        }

        mProgressDialog = ProgressDialog.show(this, "", "正在加载...");
        new Thread() {
            @Override
            public void run() {
                Uri mImgUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                ContentResolver cr = AblumActivity.this.getContentResolver();
                Cursor cursor = cr.query(mImgUri, null, MediaStore.Images.Media.MIME_TYPE + "= ? or " + MediaStore
                        .Images.Media
                        .MIME_TYPE + "= ?", new String[]{"image/jpeg", "image/png"}, MediaStore.Images.Media
                        .DATE_MODIFIED);
                Set<String> mDirPath = new HashSet<String>(); // 为了避免重复扫描
                while (cursor.moveToNext()) {
                    // 得到图片路径
                    String path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
                    File parentFile = new File(path).getParentFile();
                    if (parentFile == null)
                        continue;
                    String dirPath = parentFile.getAbsolutePath();
                    FolderBean folderBean = null;
                    if (mDirPath.contains(dirPath)) {
                        continue;
                    } else {
                        mDirPath.add(dirPath);
                        folderBean = new FolderBean();
                        folderBean.setDir(dirPath);
                        folderBean.setFirstImgPath(path);
                    }
                    if (parentFile.list() == null)
                        continue;
                    int picSize = parentFile.list(new FilenameFilter() {
                        @Override
                        public boolean accept(File dir, String filename) {
                            if (filename.endsWith(".jpg") || filename.endsWith("jpeg") || filename.endsWith(".png"))
                                return true;
                            return false;
                        }
                    }).length;
                    folderBean.setCount(picSize);
                    mFolderBeans.add(folderBean);
                    if (picSize > mMaxCount) { // 默认显示文件最多的
                        mMaxCount = picSize;
                        mCurrentDir = parentFile;
                    }
                }
                cursor.close();
                mHandler.sendEmptyMessage(FINISH_LOAD);
            }
        }.start();
    }

    private void initEvents() {
        mRl_bottom.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.showAsDropDown(mRl_bottom, 0, 0);
                Util.lightOff(AblumActivity.this);
            }
        });
        mIv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        mTv_operation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent data = new Intent();
                data.putStringArrayListExtra(ArgsConstants.PICS, (ArrayList<String>) AblumImageAdapter.mSelectedImg);
                setResult(Activity.RESULT_OK,data);
                finish();
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        LogUtil.showInfoLog("onDestroy", "ablum activity onDestroy");
        android.os.Process.killProcess(android.os.Process.myPid());
    }
}
